package service

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"user-service/basic/global"
	__ "user-service/basic/proto"
	"user-service/internal/model"
)

type UserService struct {
	__.UnimplementedUserServer
}

func (s *UserService) Register(_ context.Context, req *__.RegisterReq) (resp *__.RegisterResp, err error) {

	codeKey := "SendSmsCode" + req.Mobile

	code, err := global.Rdb.Get(global.Ctx, codeKey).Result()
	if err != nil {
		return nil, fmt.Errorf("未接收到验证码")
	}

	if req.Code != code {
		return nil, fmt.Errorf("验证码错误")
	}

	user := model.User{}

	global.DB.Debug().Where("mobile = ?", req.Mobile).First(&user)

	if user.ID != 0 {
		return nil, fmt.Errorf("该用户已注册")
	}

	user = model.User{
		NickName: "默认昵称" + strconv.Itoa(rand.Intn(1000)),
		Password: req.Password,
		Mobile:   req.Mobile,
		Avatar:   "morentouxiang.png",
	}

	err = global.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, err
	}

	resp = &__.RegisterResp{Id: int64(user.ID)}

	return resp, nil

}

func (s *UserService) Login(_ context.Context, req *__.LoginReq) (resp *__.LoginResp, err error) {

	login := model.User{}

	global.DB.Debug().Where("mobile = ?", req.Mobile).First(&login)

	if login.ID == 0 {
		return nil, fmt.Errorf("当前用户尚未注册")
	}

	codeKey := "SendSmsCode" + req.Mobile

	code, err := global.Rdb.Get(global.Ctx, codeKey).Result()
	if err != nil {
		return nil, fmt.Errorf("未接收到验证码")
	}

	if req.Code != code {
		return nil, fmt.Errorf("验证码错误")
	}

	resp = &__.LoginResp{
		Id:       int64(login.ID),
		NickName: login.NickName,
	}

	return resp, nil

}
